package org.gdpu.Service.Impl;

import com.sun.net.httpserver.Authenticator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.Service.MailboxService;
import org.gdpu.Service.StudentService;
import org.gdpu.Service.UserService;
import org.gdpu.action.StudentAction;
import org.gdpu.base.DaoSupport;
import org.gdpu.model.*;
import org.gdpu.util.ChangeTime;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by HEWI2 on 2/17/14.
 */

@Service
@Transactional
public class MailboxServiceImpl extends DaoSupport<Mailbox> implements MailboxService {

    private final static Logger logger = LogManager.getLogger(MailboxServiceImpl.class);
    private StudentService studentService;

    @Override
    public Mailbox createMailbox(String stuId, String title, String message) {
        Mailbox mailbox = new Mailbox();
        mailbox.setStudent(studentService.findStudent("studentId", Integer.valueOf(stuId)).get(0));
        mailbox.setTitle(title.trim());
        mailbox.setMessage(message.trim());
        mailbox.setMailboxState(MailboxState.NOT_DEAL);
        mailbox.setPublishDate(ChangeTime.parseDate(ChangeTime.getCurrentDate()));
        try {
            this.save(mailbox);
        } catch (Exception e) {
            logger.error(e);
            return null;
        }
        return mailbox.getId() > 0 ? mailbox : null;
    }

    @Override
    public List<Mailbox> findMail(String key, Object value) {
        Map<String, Object> params = new HashMap<String, Object>();
        List<Mailbox> mailboxes = new ArrayList<Mailbox>();
        if ("student".equals(key)) {
            List<Student> students = studentService.findStudent("dormitory", value);
            for (int i = 0; i < students.size(); i++) {
                params.put("student", students.get(i));
                mailboxes.addAll(this.findByFields(Mailbox.class, params));
            }

        } else {
            params.put(key, value);
            mailboxes.addAll(this.findByFields(Mailbox.class, params));
        }
        return mailboxes;
    }

    @Override
    public void deleteMail(int[] mailIds) {
        for (int id : mailIds) {
            this.delete(Mailbox.class, id);
        }
    }

    @Resource(name = "studentServiceImpl")
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }
}
